import axios from "axios";
import {deleteToken, getToken} from "../utils/token";
import {state} from "./exception";
import store from "@/store";
import router from "@/routes";
import {message} from "../utils/message";

export let http = "http://localhost:8080";
// export let http = "http://work.jklin.me:8082";

export const axios_instance = axios.create({
    // 39.101.177.247
    baseURL: http,
    headers:{
        "Content-Type":
            "application/x-www-form-urlencoded"
    },
});


/**
 * 使用es6的export default导出了一个函数，导出的函数代替axios去帮我们请求数据，
 * 函数的参数及返回值如下：
 * @param {String} method  请求的方法：get、post、delete、put
 * @param {String} url     请求的url:
 * @param {Object} data    请求的参数
 * @returns {Promise}     返回一个promise对象，其实就相当于axios请求数据的返回值
 */
export async function callApi(method, url, data = null) {
    let token = await getToken();
    method = method.toLowerCase();
    let resp = null;
    if (method == 'post' || method == 'put') {
        resp = await axios_instance.post(url, data, {headers:{"token": token}});
    } else if (method == 'get' || method == 'delete') {
        resp = await axios_instance.get(url, { params: data, headers:{"token": token}});
    }else{
        console.error('未知的method'+method);
        return false;
    }
    // 若登录过期，直接设置未登录
    if(resp.data.code === state.SignatureException){
        message.warning(resp.data.message);
        store.commit("user/setIsLogin", false);
        deleteToken();
        router.history.current.name !== "Home" ? router.push({name: "Home"}) : null;
    }
    return resp.data;
}
